import defaultImg from "@/assets/image/default.png";
//异步加载图片
let imageAsync = (url) => {
  return new Promise((resolve, reject) => {
    let img = new Image();
    img.src = url;
    img.onload = () => {
      resolve();
    };
    img.onerror = (err) => {
      reject(err);
    };
  });
};

export const lazyPlugin = {
  install(app) {
    app.directive("lazy", {
      mounted(el, binding) {
        el.src = defaultImg;
        const io = new IntersectionObserver((entries) => {
          entries.forEach((item) => {
            if (item.isIntersecting) {
              //使用异步加载图片
              imageAsync(binding.value)
                .then(() => {
                  el.src = binding.value;
                })
                .catch((error) => {
                  console.log(error);
                });
              io.unobserve(item.target);
            }
          });
        });
        io.observe(el);
      },
    });
  },
};